<template>
  <Header :check="1"
          @getUserInfo="getUserInfo" />
  <div class="clear_nav"></div>
  <div id="trade">
    <div class="top">
      <h1>{{ $t("hl_priceChange") }}</h1>
      <div class="more">
        <div></div>
        <p>BOSS</p>
      </div>
      <div class="chart"
           id="myChart"></div>

      <h4>{{ $t("hl_tab2") }}</h4>
    </div>

    <div class="section">
      <p>{{ $t("hl_sell") }}BOSS</p>
      <div class="box">
        <input type="Number"
               :placeholder="$t('hl_inputSell')"
               v-model="sellAmount" />
        <h5 @click="sellAmount = parseFloat(coinBalance).toFixed(4)">
          {{ $t("hl_max") }}
        </h5>
      </div>
      <div>
        <h6>
          BOSS{{ $t("hl_balance") }}: {{ parseFloat(coinBalance).toFixed(4) }}
        </h6>
        <h6>
          {{ $t("hl_price") }}:
          {{ coinPrice > 0 ? parseFloat(1 / coinPrice).toFixed(8) : 0 }} USDT
        </h6>
      </div>
    </div>

    <div class="section">
      <p>{{ $t("hl_willGetUSDT") }}</p>
      <div class="box">
        <input type="Number"
               disabled
               :placeholder="$t('hl_willGetUSDT')"
               v-model="willGet" />
        <p></p>
      </div>
      <div>
        <h6>
          USDT{{ $t("hl_balance") }}: {{ parseFloat(usdtBalance).toFixed(4) }}
        </h6>
        <p></p>
      </div>
    </div>

    <div class="btn"
         @click="sellClick()">{{ $t("hl_sell") }}</div>
  </div>
</template>

<script setup>
import { api_priceList } from "../request/api";
import { ref, reactive, watch, onMounted } from "vue";
import {
  showFailToast,
  showSuccessToast,
  showLoadingToast,
  closeToast,
} from "vant";
import {
  getFloat,
  getDotcAllowance,
  getCtcAllowance,
  getEstimateGas,
} from "../utils/common";
import { useRouter } from "vue-router";
import i18n from "@/lang";
import * as echarts from "echarts";
import api from "../dapp/api";

import "echarts-liquidfill";
const router = useRouter();

let address = ref("");
// onMounted(() => {
//   drawchart();
// });

let conContract, coinContract, usdtContract, allowContract, web3;
let usdtBalance = ref(0);
let coinBalance = ref(0);
let coinPrice = ref(0);
let sellAmount = ref("");
let willGet = ref("");

watch(sellAmount, (newValue, oldValue) => {
  if (Number(coinPrice.value) > 0)
  {
    willGet.value = parseFloat(
      Number(sellAmount.value) * Number(1 / coinPrice.value) * 0.93
    ).toFixed(8);
  }
});

let gasPrice = ref(0);
// 那得的数据
function getUserInfo (obj) {
  address.value = obj.address;
  web3 = obj.web3;
  gasPrice.value = obj.gasPrice;

  conContract = new obj.web3.eth.Contract(conAbi, api.conAddress);
  usdtContract = new obj.web3.eth.Contract(tongAbi, api.usdtAddress);
  coinContract = new obj.web3.eth.Contract(ctcAbi, api.coinAddress);
  allowContract = new obj.web3.eth.Contract(allowanceAbi, api.allowanceAddress);
  getBalance(obj);

  getPriceList();
}

async function getBalance (obj) {
  usdtContract.methods
    .balanceOf(address.value)
    .call()
    .then(async (res) => {
      usdtBalance.value = obj.web3.utils.fromWei(res, "ether");
    });

  coinContract.methods
    .balanceOf(address.value)
    .call()
    .then(async (res) => {
      coinBalance.value = obj.web3.utils.fromWei(res, "ether");
    });

  conContract.methods
    .getTokenPrice()
    .call()
    .then(async (res) => {
      coinPrice.value = parseFloat(Number(res) / 10000).toFixed(4);
    });
}

function drawchart () {
  const chartDom = document.getElementById("myChart");
  const myChart = echarts.init(chartDom);

  let option = {
    grid: {
      top: "10%",
      height: "70%",
      right: "44px",
      left: "15%",
    },
    xAxis: {
      type: "category",
      data: xList.value,
      axisLabel: {
        color: "#000",
      },
    },
    yAxis: {
      type: "value",
      nameTextStyle: {
        color: "#fff",
      },
      axisLabel: {
        color: "#000",
      },
    },
    dataZoom: [
      {
        startValue: yList.value.length - 7 >= 0 ? yList.value.length - 7 : 0,
        type: "slider",
        // start: 50,
        // end: 100,
      },
    ],
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#1296db",
        },
      },
    },
    series: [
      {
        data: yList.value,
        type: "line",
        barWidth: "60%",
        smooth: true,
        lineStyle: {
          color: "#1296db",
        },
        symbol: "circle",
        itemStyle: {
          normal: {
            color: "#1296db",
            // 拐点上显示数值
            borderColor: "#1296db", // 拐点边框颜色
          },
        },
        label: {
          show: true,
          position: "top",
        },
      },
    ],
  };
  myChart.setOption(option);
}

let xList = ref([]);
let yList = ref([]);
function getPriceList (params) {
  conContract.methods
    .getTimesPrices()
    .call()
    .then(async (res) => {
      let arrT = res.tim;
      let arrP = res.pri;

      if (arrT.length && arrP.length)
      {
        if (arrT.length == arrP.length)
        {
          for (let index = 0; index < arrT.length; index++)
          {
            const element = arrT[index];
            const element2 = arrP[index];

            //2025-6-17 20:10 时间戳 1750162290

            // 86400

            if (element2 != 0)
            {

              let xt = element * 86400 + 1750162290;
              yList.value.push(parseFloat(10000 / element2).toFixed(8));
              // console.log(element2);

              xList.value.push(timestampToTime(xt));
            }

          }
          drawchart();
        }
      }
    });
}
function timestampToTime (timestamp) {
  // 如果是秒级时间戳（10位），乘以1000转换为毫秒
  const date = new Date(timestamp * 1000);
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份补零（01-12）
  const day = String(date.getDate()).padStart(2, "0"); // 日期补零（01-31）

  return `${month}/${day}`;
}

async function sellClick () {
  if (!coinContract)
  {
    return;
  }

  if (Number(sellAmount.value) < 10)
  {
    let min = i18n.global.t("hl_sellCoin") + "最小为" + "10";
    showFailToast(min);
    return;
  }

  if (Number(sellAmount.value) > Number(coinBalance.value))
  {
    showFailToast(i18n.global.t("hl_noMoney"));
    return;
  }

  let a = Number(sellAmount.value);
  if (a > 0)
  {
    a -= 0.00001;
  }

  await getCtcAllowance(coinContract, allowContract, api.conAddress);
  try
  {
    const aa = conContract.methods.sell(
      web3.utils.toWei(a.toString(), "ether")
    );

    const bb = await getEstimateGas(aa, address.value);

    await aa
      .send({
        from: address.value,
        gas: bb || 400000,
        gasPrice: gasPrice.value,
      })
      .on("transactionHash", (hash) => {
        showLoadingToast({
          message: i18n.global.t("hl_waitLink"),
          forbidClick: true,
          duration: 0,
        });
      })
      .on("receipt", (receipt) => {
        closeToast();
        showSuccessToast(i18n.global.t("hl_opSucc"));
        setTimeout(() => {
          closeToast();
          location.reload();
        }, 2500);
      })
      .on("error", (error, receipt) => {
        closeToast();
        showFailToast(i18n.global.t("hl_opFail"));
      });
  } catch (e)
  {
    console.log("e :>> ", e);
  }
}
</script>

<style scoped lang="less">
#trade {
  padding: 10px 0;

  .top {
    width: 100%;

    .more {
      display: flex;
      align-items: center;
      justify-content: center;

      div {
        width: 16px;
        height: 16px;
        background: #1296db;
        margin-right: 12px;
      }
    }

    .chart {
      width: 100%;
      height: 90vw;
    }

    h1 {
      width: 100%;
      margin: 10px auto;
      color: black;
      text-align: center;
      font-size: 18px;
      font-weight: bolder;
    }

    h4 {
      width: 50%;
      margin: 20px auto;
      // border-radius: 4px;
      height: 40px;
      line-height: 40px;
      // border: 1px solid #1296db;
      color: #1296db;
      text-align: center;
      font-size: 18px;
    }
  }

  .section {
    width: 100%;
    margin-bottom: 12px;
    padding: 0 3%;

    p {
      font-size: 16px;
      color: #696565;
      margin-bottom: 4px;
    }

    div {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 44px;
    }

    .box {
      border: 1px solid black;
      background: white;
      h5 {
        background: #d9d9d9;
        height: 42px;
        line-height: 42px;
        padding: 1px 10px;
        color: #1296db;
      }

      input {
        height: 100%;
        line-height: 100%;
        color: black;
        font-size: 16px;
        max-width: 80%;
      }
    }
  }

  .btn {
    width: 50%;
    border-radius: 4px;
    height: 40px;
    background: #1296db;
    color: white;
    font-size: 16px;
    margin: 12px auto;
    text-align: center;
    line-height: 40px;
  }
}
</style>
